package com.maimang.platform.aspect;

import com.maimang.platform.annotation.ApiLog;
import com.maimang.platform.common.entity.SysApiLog;
import com.maimang.platform.common.entity.SysUser;
import com.maimang.platform.common.utils.ShiroUtils;
import com.maimang.platform.common.utils.http.ServletUtils;
import com.maimang.platform.enums.BusinessStatus;
import com.maimang.platform.json.JSON;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.manager.AsyncManager;
import com.maimang.platform.manager.factory.AsyncFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 远程API接口请求日志记录处理
 * 日志切面类实现：
 * 1.在类上使用 @Component 注解 把切面类加入到IOC容器中
 * 2.在类上使用 @Aspect 注解 使之成为切面类
 *
 * @author Rocky
 */
@Aspect
@Component
public class ApiLogAspect {
	private static final Logger log = LoggerFactory.getLogger(ApiLogAspect.class);

	// 配置织入点
	@Pointcut("@annotation(com.maimang.platform.annotation.ApiLog)")
	public void logPointCut() {
	}

	/**
	 * 前置通知 用于拦截操作
	 *
	 * @param joinPoint 切点
	 */
	@AfterReturning(pointcut = "logPointCut()")
	public void doBefore(JoinPoint joinPoint) {
		handleLog(joinPoint, null);
	}

	/**
	 * 拦截异常操作
	 *
	 * @param joinPoint
	 * @param e
	 */
	@AfterThrowing(value = "logPointCut()", throwing = "e")
	public void doAfter(JoinPoint joinPoint, Exception e) {
		handleLog(joinPoint, e);
	}

	protected void handleLog(final JoinPoint joinPoint, final Exception e) {
		try {
			// 获得注解
			ApiLog controllerLog = getAnnotationLog(joinPoint);
			if (controllerLog == null) {
				return;
			}

			// 获取当前的用户
			SysUser currentUser = ShiroUtils.getSysUser();

			// *========数据库日志=========*//
			SysApiLog apiLog = new SysApiLog();

			apiLog.setStatus(BusinessStatus.SUCCESS.ordinal());
			// 请求的地址
			String ip = ShiroUtils.getIp();
			apiLog.setUserHost(ip);

			apiLog.setApiUrl(ServletUtils.getRequest().getRequestURI());
			if (currentUser != null) {
				apiLog.setUserId(currentUser.getUserId());
				apiLog.setUserName(currentUser.getLoginName());
				if (StringUtils.isNotNull(currentUser.getDept()) && StringUtils.isNotEmpty(currentUser.getDeptName())) {
					apiLog.setDeptName(currentUser.getDeptName());
				}
				if (currentUser.getDeptId() != null) {
					apiLog.setDeptId(currentUser.getDeptId().toString());
				}
			}

			if (e != null) {
				apiLog.setStatus(BusinessStatus.FAIL.ordinal());
				apiLog.setResponseMessage(StringUtils.substring(e.getMessage(), 0, 2000));
			}
			// 设置方法名称
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = joinPoint.getSignature().getName();
			apiLog.setMethod(className + "." + methodName + "()");
			// 处理设置注解上的参数
			getControllerMethodDescription(controllerLog, apiLog);
			// 保存数据库
			AsyncManager.me().execute(AsyncFactory.recordApiLog(apiLog));
		} catch (Exception exp) {
			// 记录本地异常日志
			log.error("==前置通知异常==");
			log.error("异常信息:{}", exp.getMessage());
			exp.printStackTrace();
		}
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 *
	 * @param log    日志
	 * @param apiLog 接口请求日志
	 * @return 方法描述
	 * @throws Exception
	 */
	public void getControllerMethodDescription(ApiLog log, SysApiLog apiLog) throws Exception {
		// 设置action动作
		// apiLog.s(log.businessType().ordinal());
		// 设置标题
		apiLog.setTitle(log.title());
		// 设置操作人类别
		apiLog.setUserType(log.operatorType().ordinal());
		// 是否需要保存request，参数和值
		if (log.isSaveRequestData()) {
			// 获取参数的信息，传入到数据库中。
			setRequestValue(apiLog);
		}
	}

	/**
	 * 获取请求的参数，放到log中
	 *
	 * @param apiLog 操作日志
	 * @throws Exception 异常
	 */
	private void setRequestValue(SysApiLog apiLog) throws Exception {
		Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
		String params = JSON.marshal(map);
		apiLog.setRequestParam(StringUtils.substring(params, 0, 255));
	}

	/**
	 * 是否存在注解，如果存在就获取
	 */
	private ApiLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(ApiLog.class);
		}
		return null;
	}
}
